<template>
  <div class="exportdata-container">
    <SimpleSidebar />
    <div class="main-content">
      <el-card class="export-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <el-button type="primary" link @click="goBack">
                <el-icon><ArrowLeft /></el-icon>
                返回
              </el-button>
            </div>
            <div class="header-right">
              <el-icon class="header-icon"><Download /></el-icon>
              <span>数据导出</span>
            </div>
          </div>
        </template>

        <div class="export-form">
          <el-form :model="exportForm" label-width="120px">
            <el-form-item label="导出类型">
              <el-select v-model="exportForm.type" placeholder="请选择导出类型" style="width: 100%">
                <el-option label="视频热度数据" value="video">
                  <template #default>
                    <el-icon><VideoCamera /></el-icon>
                    <span style="margin-left: 8px">视频热度数据</span>
                  </template>
                </el-option>
                <el-option label="标签热度数据" value="tag">
                  <template #default>
                    <el-icon><PriceTag /></el-icon>
                    <span style="margin-left: 8px">标签热度数据</span>
                  </template>
                </el-option>
                <el-option label="用户喜好数据" value="user">
                  <template #default>
                    <el-icon><User /></el-icon>
                    <span style="margin-left: 8px">用户喜好数据</span>
                  </template>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="导出格式">
              <el-radio-group v-model="exportForm.format">
                <el-radio label="csv">
                  <el-icon><Document /></el-icon>
                  <span>CSV格式</span>
                </el-radio>
                <el-radio label="excel">
                  <el-icon><Document /></el-icon>
                  <span>Excel格式</span>
                </el-radio>
                <el-radio label="json">
                  <el-icon><Document /></el-icon>
                  <span>JSON格式</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="导出进度" v-if="isExporting">
              <el-progress
                  :percentage="exportProgress"
                  :status="exportStatus"
                  :stroke-width="20"
                  :text-inside="true"
                  :show-text="true"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                  type="primary"
                  :loading="isExporting"
                  :disabled="isExporting"
                  @click="handleExport"
                  class="export-button"
              >
                <template #icon>
                  <el-icon><Download /></el-icon>
                </template>
                {{ isExporting ? '正在导出...' : '开始导出' }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

      <el-card class="history-card" shadow="hover" v-if="exportHistory.length > 0">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><Clock /></el-icon>
            <span>导出历史</span>
          </div>
        </template>

        <el-table :data="exportHistory" style="width: 100%" stripe>
          <el-table-column prop="type" label="数据类型" width="120">
            <template #default="scope">
              <el-tag :type="getTypeTag(scope.row.type)">
                {{ getTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="format" label="文件格式" width="100">
            <template #default="scope">
              <el-tag type="info">{{ scope.row.format.toUpperCase() }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="time" label="导出时间" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
                {{ scope.row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                  v-if="scope.row.status === 'success'"
                  type="primary"
                  link
                  @click="handleDownload(scope.row)"
              >
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, VideoCamera, PriceTag, User, Document, Clock, ArrowLeft } from '@element-plus/icons-vue'
import SimpleSidebar from "@/views/chart/SimpleSidebar.vue"
import { useRouter } from 'vue-router'
import { useAnalysisStore } from '@/store/analysis'

const router = useRouter()
const analysisStore = useAnalysisStore()
const exportData = ref(null)

const exportForm = reactive({
  type: 'video',
  format: 'csv'
})

const exportProgress = ref(0)
const exportStatus = ref('')
const isExporting = ref(false)
const exportHistory = ref([])

//直接从store获取数据
onMounted(() => {
  exportData.value = analysisStore.getExportData()
  if (!exportData.value) {
    ElMessage.warning('未获取到导出数据，请返回数据展示页面重试')
    router.push({name: 'showdata'})
  }
})

const goBack = () => {
  router.back()
}

const handleExport = async () => {
  if (isExporting.value) return

  isExporting.value = true
  exportProgress.value = 0
  exportStatus.value = ''

  try {
    // 直接从store获取数据
    const dataToExport = exportData.value[exportForm.type]

    if (!dataToExport) {
      throw new Error('未找到要导出的数据')
    }

    // 模拟导出进度
    const progressInterval = setInterval(() => {
      if (exportProgress.value < 100) {
        exportProgress.value += 20
      } else {
        clearInterval(progressInterval)
        // 先显示成功消息
        ElMessage.success('导出成功！')
        // 再更新状态
        exportStatus.value = 'success'
        isExporting.value = false

        // 添加到历史记录
        exportHistory.value.unshift({
          type: exportForm.type,
          format: exportForm.format,
          time: new Date().toLocaleString(),
          status: 'success',
          data: dataToExport
        })
      }
    }, 500)
  } catch (error) {
    console.error('导出失败:', error)
    exportStatus.value = 'exception'
    isExporting.value = false
    ElMessage.error('导出失败，请重试')
  }
}

const handleDownload = (record) => {
  // 实现下载逻辑
  const data = record.data
  let content = ''

  switch (record.format) {
    case 'csv':
      content = convertToCSV(data)
      break
    case 'json':
      content = JSON.stringify(data, null, 2)
      break
    case 'excel':
      // 这里需要实现Excel转换逻辑
      content = convertToExcel(data)
      break
  }

  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `export_${record.type}_${new Date().getTime()}.${record.format}`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

const convertToCSV = (data) => {
  if (!data || !data.length) return ''

  const headers = Object.keys(data[0])
  const csvRows = [headers.join(',')]

  data.forEach(item => {
    const values = headers.map(header => {
      const value = item[header]
      return typeof value === 'string' ? `"${value}"` : value
    })
    csvRows.push(values.join(','))
  })

  return csvRows.join('\n')
}

const convertToExcel = (data) => {
  // 这里需要实现Excel转换逻辑
  // 可以使用第三方库如 xlsx 来实现
  return JSON.stringify(data)
}

const getTypeTag = (type) => {
  switch (type) {
    case 'video': return 'primary'
    case 'tag': return 'warning'
    case 'user': return 'success'
    default: return 'info'
  }
}

const getTypeText = (type) => {
  switch (type) {
    case 'video': return '视频热度'
    case 'tag': return '标签热度'
    case 'user': return '用户喜好'
    default: return type
  }
}
</script>

<style scoped>
.exportdata-container {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #b6e0ff 0%, #f7d9ff 100%);
}

.main-content {
  flex: 1;
  padding: 20px;
  margin-left: 220px;
  width: calc(100% - 220px);
}

.export-card, .history-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border: none;
  border-radius: 8px;
  overflow: hidden;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.export-card:hover, .history-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-icon {
  margin-right: 8px;
  font-size: 20px;
  color: #409eff;
}

.export-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.export-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.export-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

:deep(.el-radio) {
  margin-right: 16px;
}

:deep(.el-radio__label) {
  display: flex;
  align-items: center;
  gap: 4px;
}

:deep(.el-progress-bar__outer) {
  border-radius: 10px;
  background-color: #f5f7fa;
}

:deep(.el-progress-bar__inner) {
  border-radius: 10px;
  transition: all 0.3s ease;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebeef5;
  width: 100%;
}

:deep(.el-table__header) {
  background-color: #f8f9fa;
}

:deep(.el-table__row) {
  transition: all 0.3s ease;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
  font-size: 12px;
}

:deep(.el-button--primary.is-link) {
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

:deep(.el-button--primary.is-link:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-radio) {
  margin-right: 0;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #409eff;
}
</style>